package com.jiazaibendi.lottery.service.impl;

import com.jiazaibendi.lottery.dao.domain.Prize;
import com.jiazaibendi.lottery.dao.domain.Scheme;
import com.jiazaibendi.lottery.dao.domain.UserFre;
import com.jiazaibendi.lottery.dao.domain.UserFreExample;
import com.jiazaibendi.lottery.dao.mapper.PrizeMapper;
import com.jiazaibendi.lottery.dao.mapper.SchemeMapper;
import com.jiazaibendi.lottery.dao.mapper.UserFreMapper;
import com.jiazaibendi.lottery.model.PrizeVo;
import com.jiazaibendi.lottery.service.OperationService;
import com.jiazaibendi.lottery.service.PrizePoolService;
import com.jiazaibendi.lottery.service.RecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * description
 *
 * @author echo_kai
 * @version 1.0
 * @date 2021/08/07
 */
@Service
@Slf4j
public class OperationServiceImpl implements OperationService {

    @Resource
    private UserFreMapper userFreMapper;

    @Resource
    private SchemeMapper schemeMapper;

    @Resource
    private PrizeMapper prizeMapper;

    @Resource
    private PrizePoolService prizePoolService;

    @Resource
    private RecordService recordService;

    @Override
    public int queryUserRemainingFrequency(long userId, long schemeId) {
        UserFreExample example = new UserFreExample();
        example.createCriteria().andUserIdEqualTo(userId).andSchemeIdEqualTo(schemeId);
        List<UserFre> userFreList = userFreMapper.selectByExample(example);
        UserFre userFre;
        if (CollectionUtils.isEmpty(userFreList)) {
            userFre = createUserFre(userId, schemeId);
        } else {
            userFre = userFreList.get(0);
        }
        // 如果是昨天或之前更新的
        if (userFre.getLastUpdateBashFreTime().before(Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant()))) {
            Scheme scheme = schemeMapper.selectByPrimaryKey(schemeId);
            userFre.setCurrentFre(scheme.getBaseFre());
            userFre.setLastUpdateBashFreTime(new Date());
            userFreMapper.updateByPrimaryKeySelective(userFre);
        }
        return userFre.getCurrentFre();
    }

    private UserFre createUserFre(long userId, long schemeId) {
        Scheme scheme = schemeMapper.selectByPrimaryKey(schemeId);
        UserFre userFre = new UserFre();
        userFre.setUserId(userId);
        userFre.setSchemeId(schemeId);
        userFre.setLastUpdateBashFreTime(new Date());
        userFre.setCurrentFre(scheme.getBaseFre());
        userFreMapper.insert(userFre);
        return userFre;
    }

    @Override
    public void addFrequencyByFriendCircle(long userId, long schemeId) {
        Scheme scheme = schemeMapper.selectByPrimaryKey(schemeId);
        UserFreExample example = new UserFreExample();
        example.createCriteria().andUserIdEqualTo(userId).andSchemeIdEqualTo(schemeId);
        UserFre userFre = userFreMapper.selectByExample(example).get(0);
        // 如果是昨天或之前更新的
        if (userFre.getLastPyqShareTime() == null || userFre.getLastPyqShareTime().before(Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant()))) {
            userFre.setLastPyqShareTime(new Date());
            userFre.setCurrentFre(userFre.getCurrentFre() + scheme.getPyqFre());
            userFreMapper.updateByPrimaryKey(userFre);
        }
    }

    @Override
    public boolean addFrequencyByFriend(long userId, long schemeId) {
        Scheme scheme = schemeMapper.selectByPrimaryKey(schemeId);
        UserFreExample example = new UserFreExample();
        example.createCriteria().andUserIdEqualTo(userId).andSchemeIdEqualTo(schemeId);
        UserFre userFre = userFreMapper.selectByExample(example).get(0);
        // 如果是昨天或之前更新的
        if (userFre.getLastFriendShareTime() == null || userFre.getLastFriendShareTime().before(Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant()))) {
            userFre.setLastFriendShareTime(new Date());
            userFre.setCurrentFre(userFre.getCurrentFre() + scheme.getFriendFre());
            userFreMapper.updateByPrimaryKey(userFre);
            return true;
        }
        return false;
    }

    @Override
    public boolean addFrequencyByGroup(long userId, long schemeId) {
        Scheme scheme = schemeMapper.selectByPrimaryKey(schemeId);
        UserFreExample example = new UserFreExample();
        example.createCriteria().andUserIdEqualTo(userId).andSchemeIdEqualTo(schemeId);
        UserFre userFre = userFreMapper.selectByExample(example).get(0);
        // 如果是昨天或之前更新的
        if (userFre.getLastGroupShareTime() == null || userFre.getLastGroupShareTime().before(Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant()))) {
            userFre.setLastGroupShareTime(new Date());
            userFre.setCurrentFre(userFre.getCurrentFre() + scheme.getGroupFre());
            userFreMapper.updateByPrimaryKey(userFre);
            return true;
        }
        return false;
    }

    @Override
    public void decreaseFrequency(long userId, long schemeId) {
        UserFreExample example = new UserFreExample();
        example.createCriteria().andUserIdEqualTo(userId).andSchemeIdEqualTo(schemeId);
        UserFre userFre = userFreMapper.selectByExample(example).get(0);
        userFre.setCurrentFre(userFre.getCurrentFre() - 1);
        userFreMapper.updateByPrimaryKey(userFre);
    }

    @Override
    public PrizeVo playGame(long userId, long schemeId) {
        if (queryUserRemainingFrequency(userId, schemeId) <= 0) {
            return new PrizeVo(0,0,0,0,"","无抽奖次数");
        }
        recordService.addAllJoinPeopleNumber(schemeId);
        long prizeId = prizePoolService.getPrizeIdFromPrizePool(schemeId);
        // todo:优化兼容
        if (recordService.queryHaveEntity(schemeId, userId, prizeId) || recordService.queryHaveEnvelope(schemeId, userId, prizeId) || recordService.queryHaveCoupon(schemeId, userId, prizeId)) {
            prizePoolService.addPrizeToPrizePool(schemeId, Collections.singletonList(prizeId));
            prizeId = 0;
        }
        Prize prize = prizeMapper.selectByPrimaryKey(prizeId);
        PrizeVo prizeVo = new PrizeVo();
        prizeVo.setPrizeId(prizeId);
        if (prize != null) {
            prizeVo.setSchemeId(schemeId);
            prizeVo.setUserId(userId);
            prizeVo.setDesc(prize.getName());
            String code = prizePoolService.getACodeFromEnvelopePool(schemeId, prizeId);
            // todo:优化兼容
            if (prizeId>5 && prizeId<10 && StringUtils.isEmpty(code)){
                prize.setRemaining(prize.getRemaining() + 1);
                prizeMapper.updateByPrimaryKey(prize);
                prizeVo.setPrizeId(0);
            }
            prizeVo.setCode(code);
        }
        prizeVo.setRecordId(recordService.gainAnyPrize(userId, schemeId, prizeId));
        decreaseFrequency(userId, schemeId);
        return prizeVo;
    }
}
